package com.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.myapp.MyApp;
import com.myview.CustomProgressDialog;
import com.util.GlideUtils;
import com.util.InfoEventMessage;
import com.util.MyLog;
import com.util.RequestManager;
import com.xiaochun.hxhj.CollectVideoActivity;
import com.xiaochun.hxhj.JingxiaoshangActivity;
import com.xiaochun.hxhj.LoginActivity;
import com.xiaochun.hxhj.MessageCommitActivity;
import com.xiaochun.hxhj.R;
import com.xiaochun.hxhj.VipActivity;
import com.xiaochun.hxhj.WebviewActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;


public class MineFragment extends Fragment implements View.OnClickListener {
    @BindView(R.id.ll_info)
    LinearLayout ll_info;
    @BindView(R.id.tv_login)
    TextView tv_login;
    @BindView(R.id.img_userlogo)
    ImageView img_userlogo;
    @BindView(R.id.tv_username)
    TextView tv_username;
    @BindView(R.id.tv_student_num)
    TextView tv_student_num;
    @BindView(R.id.ll_set)
    LinearLayout ll_set;
    @BindView(R.id.ll_message)
    LinearLayout ll_message;
    @BindView(R.id.img_share)
    ImageView img_share;
    @BindView(R.id.tv_course_remind)
    TextView tv_course_remind;
    @BindView(R.id.tv_course_notes)
    TextView tv_course_notes;
    @BindView(R.id.ll_teacher)
    LinearLayout ll_teacher;
    @BindView(R.id.ll_jifen)
    LinearLayout ll_jifen;
    @BindView(R.id.ll_addr)
    LinearLayout ll_addr;
    @BindView(R.id.ll_msg)
    LinearLayout ll_msg;
    @BindView(R.id.ll_myinfo)
    LinearLayout ll_myinfo;
    @BindView(R.id.ll_video_collect)
    LinearLayout ll_video_collect;
    @BindView(R.id.tv_vip_content_one)
    TextView tv_vip_content_one;
    @BindView(R.id.ll_gobuy_vip)
    LinearLayout ll_gobuy_vip;
    @BindView(R.id.tv_vip_content_two)
    TextView tv_vip_content_two;
    @BindView(R.id.tv_vip_content_three)
    TextView tv_vip_content_three;
    @BindView(R.id.ll_jxs)
    LinearLayout ll_jxs;
    @BindView(R.id.view_jxs_line)
    View view_jxs_line;
    @BindView(R.id.rl_vip)
    RelativeLayout rl_vip;


    private Context mcontext;
    private MyApp myapp;
    private View view;
    private CustomProgressDialog customProgressDialog;
    private SharedPreferences sharedPreferences;
    private String token;
    private String is_agent;
    private String vip_expire;
    private String is_vip;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.e("Activity:", this.getClass().getName().toString());
        view = inflater.inflate(R.layout.fragment_mine, container, false);
        mcontext = getActivity();
        myapp = (MyApp) mcontext.getApplicationContext();
        EventBus.getDefault().register(this);
        ButterKnife.bind(this, view);
        sharedPreferences = mcontext.getSharedPreferences("userinfo", Activity.MODE_MULTI_PROCESS);
        token = sharedPreferences.getString("token", "");
        customProgressDialog = new CustomProgressDialog(mcontext, "", R.style.CommProgressDialog);
        WindowManager.LayoutParams params = customProgressDialog.getWindow().getAttributes();
        params.alpha = 0.7f;//取值为0-1之间  0是全透明，1是不透明
        params.dimAmount = 0f;   //取值为0-1之间  1是全黑
//		params.width = 180;//设置进度条的宽度
//		params.height = 180;//设置进度条的宽度
        customProgressDialog.getWindow().setAttributes(params);
//        customProgressDialog.show();
        initView();

        initLin();
//        getData();
        return view;

    }


    private void initView() {
        String avatar = sharedPreferences.getString("avatar", "");
        String nickname = sharedPreferences.getString("nickname", "");
        String student_id = sharedPreferences.getString("student_id", "");

        if ("".equals(token)) {
            ll_info.setVisibility(View.GONE);
            tv_login.setVisibility(View.VISIBLE);
            tv_username.setText("nickname");
            tv_student_num.setText("");
        } else {
            ll_info.setVisibility(View.VISIBLE);
            tv_login.setVisibility(View.GONE);
            tv_username.setText(nickname);
            tv_student_num.setText("学号：" + student_id);

            if (avatar.contains("http")) {
                GlideUtils.loadCircleImage(mcontext, avatar, img_userlogo);

            } else {
                img_userlogo.setImageResource(R.mipmap.ic_launcher);
                /*String base64String = avatar;

                //将Base64编码字符串解码成Bitmap

                byte[] decodedString = Base64.decode(base64String.split(",")[1], Base64.DEFAULT);

                Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);

                //设置ImageView图片

                img_userlogo.setImageBitmap(decodedByte);*/

            }
        }

    }

    @Subscribe
    public void onEventMainThread(InfoEventMessage event) {
        String message = event.getMessage();
        Log.e("GTPCmessage--new--order", message);


    }

    private void initLin() {
        ll_set.setOnClickListener(this);
        ll_message.setOnClickListener(this);
        tv_login.setOnClickListener(this);
        ll_myinfo.setOnClickListener(this);
        img_share.setOnClickListener(this);
        tv_course_notes.setOnClickListener(this);
        tv_course_remind.setOnClickListener(this);
        ll_teacher.setOnClickListener(this);
        ll_info.setOnClickListener(this);
        ll_addr.setOnClickListener(this);
        ll_msg.setOnClickListener(this);
        ll_jifen.setOnClickListener(this);
        ll_video_collect.setOnClickListener(this);
        ll_gobuy_vip.setOnClickListener(this);
        ll_jxs.setOnClickListener(this);
        rl_vip.setOnClickListener(this);

    }

    private void getData() {
        token = sharedPreferences.getString("token", "");
        String url = myapp.getWebConfig() + "/api/user/userInfo";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("token", token);
        MyLog.e("获取用户信息", url + "   token=" + token);
        RequestManager.getInstance(mcontext).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {


            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {
                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    JSONObject data = jsonObject.getJSONObject("data");

                    String user_id = data.getString("user_id");
                    String username = data.getString("username");
                    String nickname = data.getString("nickname");
                    String mobile = data.getString("mobile");
                    String avatar = data.getString("avatar");
                    String score = data.getString("score");
                    String student_id = data.getString("student_id");
                    String is_bind_wx = data.getString("is_bind_wx");
                    String token = data.getString("token");
                    is_agent = data.getString("is_agent");
                    vip_expire = data.getString("vip_expire");
                    is_vip = data.getString("is_vip");
                    sharedPreferences.edit().putString("user_id", user_id).commit();
                    sharedPreferences.edit().putString("username", username).commit();
                    sharedPreferences.edit().putString("nickname", nickname).commit();
                    sharedPreferences.edit().putString("mobile", mobile).commit();
                    sharedPreferences.edit().putString("avatar", avatar).commit();
                    sharedPreferences.edit().putString("score", score).commit();
                    sharedPreferences.edit().putString("student_id", student_id).commit();
                    sharedPreferences.edit().putString("is_bind_wx", is_bind_wx).commit();
                    sharedPreferences.edit().putString("token", token).commit();
                    sharedPreferences.edit().putString("is_agent", is_agent).commit();
                    sharedPreferences.edit().putString("vip_expire", vip_expire).commit();
                    sharedPreferences.edit().putString("is_vip", is_vip).commit();

                    msg.arg1 = 4;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                } else {
                    Message msg = new Message();
                    msg.arg1 = 12;
                    handler.sendMessage(msg);
                }
            }
        });
    }


    public Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1) {
                case 0:

                    break;
                case 1:

                    break;
                case 2:

                    break;
                case 3:


                    break;
                case 4:
                    token = sharedPreferences.getString("token", "");
                    String avatar = sharedPreferences.getString("avatar", "");
                    String nickname = sharedPreferences.getString("nickname", "");
                    String student_id = sharedPreferences.getString("student_id", "");

                    if ("".equals(token)) {
                        ll_info.setVisibility(View.GONE);
                        tv_login.setVisibility(View.VISIBLE);
                        tv_username.setText("nickname");
                        tv_student_num.setText("");
                        img_userlogo.setImageResource(R.mipmap.ic_launcher_round);

                        tv_vip_content_one.setText("登录享受会员权益");
                        tv_vip_content_two.setText("Members");
                        ll_gobuy_vip.setVisibility(View.INVISIBLE);
                        tv_vip_content_three.setText("");

                    } else {

//                        is_agent	string	代理:0=否,1=是
                        if ("0".equals(is_agent)) {
                            ll_jxs.setVisibility(View.GONE);
                            view_jxs_line.setVisibility(View.GONE);
                        } else if ("1".equals(is_agent)) {
                            ll_jxs.setVisibility(View.VISIBLE);
                            view_jxs_line.setVisibility(View.VISIBLE);
                        }

                        ll_info.setVisibility(View.VISIBLE);
                        tv_login.setVisibility(View.GONE);
                        tv_username.setText(nickname);
                        tv_student_num.setText("学号：" + student_id);

                        if ("1".equals(is_vip)) {
                            //是会员
                            tv_vip_content_one.setText("尊敬的会员用户");
                            tv_vip_content_two.setText("您已开通会员卡，可学习所有课程");
                            tv_vip_content_three.setText(vip_expire + "到期");
                            ll_gobuy_vip.setVisibility(View.INVISIBLE);
                        } else if ("0".equals(is_vip)) {
                            //不是会员
                            tv_vip_content_one.setText("开通会员");
                            tv_vip_content_two.setText("开通会员可免费学习所有课程");
                            ll_gobuy_vip.setVisibility(View.VISIBLE);
                        }
                        if (avatar.contains("http")) {
                            GlideUtils.loadCircleImage(mcontext, avatar, img_userlogo);
                        } else {
                            img_userlogo.setImageResource(R.mipmap.ic_launcher);
                /*String base64String = avatar;

                //将Base64编码字符串解码成Bitmap

                byte[] decodedString = Base64.decode(base64String.split(",")[1], Base64.DEFAULT);

                Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);

                //设置ImageView图片

                img_userlogo.setImageBitmap(decodedByte);*/

                        }

                    }
                    break;
                case 11:
                    sharedPreferences.edit().putString("user_id", "").commit();
                    sharedPreferences.edit().putString("username", "").commit();
                    sharedPreferences.edit().putString("nickname", "").commit();
                    sharedPreferences.edit().putString("mobile", "").commit();
                    sharedPreferences.edit().putString("avatar", "").commit();
                    sharedPreferences.edit().putString("score", "").commit();
                    sharedPreferences.edit().putString("student_id", "").commit();
                    sharedPreferences.edit().putString("is_bind_wx", "").commit();
                    sharedPreferences.edit().putString("token", "").commit();
                    sharedPreferences.edit().putString("is_agent", "").commit();
                    sharedPreferences.edit().putString("vip_expire", "").commit();
                    sharedPreferences.edit().putString("is_vip", "").commit();

                    if ("".equals(token)) {
                        tv_vip_content_one.setText("登录享受会员权益");
                        tv_vip_content_two.setText("Members");
                        tv_vip_content_three.setText("");
                        ll_gobuy_vip.setVisibility(View.INVISIBLE);
                        ll_info.setVisibility(View.GONE);
                        tv_login.setVisibility(View.VISIBLE);
                        tv_username.setText("");
                        tv_student_num.setText("");
                        img_userlogo.setImageResource(R.mipmap.ic_launcher_round);
                        ll_jxs.setVisibility(View.GONE);
                        view_jxs_line.setVisibility(View.GONE);
                    }


                    break;
                case 12:

                    break;
            }
        }
    };

    private boolean islogin = false;

    /**
     * 获取屏幕宽度
     */
    private void getScreenDen() {
//        dm = new DisplayMetrics();
//        heightPixels = dm.heightPixels;
//        getWindowManager().getDefaultDisplay().getMetrics(dm);

        WindowManager manager = getActivity().getWindowManager();
        DisplayMetrics dm = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(dm);
        //以要素为单位
        int width = dm.widthPixels;
        int heightPixels = dm.heightPixels;
        MyLog.e("获取屏幕高度", heightPixels + "    高度   " + width);
    }


    @Override
    public void onResume() {
        super.onResume();

        getData();

        MyLog.e("我的", "onResume");
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);

        if (!hidden) {
            getData();
        }

        MyLog.e("我的", "onHiddenChanged     " + hidden);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onClick(View view) {
        Intent intent = null;
        token = sharedPreferences.getString("token", "");
        switch (view.getId()) {
            case R.id.ll_set:
                //设置
                if ("".equals(token)) {
                    intent = new Intent(mcontext, LoginActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(mcontext, WebviewActivity.class);
                    intent.putExtra("url", myapp.getSiteurlweb() + "/#/set");
                    startActivity(intent);
                }
                break;
            case R.id.ll_message:
                //消息
                if ("".equals(token)) {
                    intent = new Intent(mcontext, LoginActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(mcontext, WebviewActivity.class);
                    intent.putExtra("url", myapp.getSiteurlweb() + "/#/news");
                    startActivity(intent);
                }
                break;
            case R.id.tv_login:
                intent = new Intent(mcontext, LoginActivity.class);
                startActivity(intent);
                break;
            case R.id.ll_myinfo:
                //用户信息
                if ("".equals(token)) {
                    intent = new Intent(mcontext, LoginActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(mcontext, WebviewActivity.class);
                    intent.putExtra("url", myapp.getSiteurlweb() + "/#/profile?token=" + token);
                    startActivity(intent);
                }
                break;
            case R.id.img_share:
                //邀请好友
                if ("".equals(token)) {
                    intent = new Intent(mcontext, LoginActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(mcontext, WebviewActivity.class);
                    intent.putExtra("url", myapp.getSiteurlweb() + "/#/share?token=" + token);
                    startActivity(intent);
                }
                break;
            case R.id.tv_course_notes:
                //课程记录
                if ("".equals(token)) {
                    intent = new Intent(mcontext, LoginActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(mcontext, WebviewActivity.class);
                    intent.putExtra("url", myapp.getSiteurlweb() + "/#/mycourses?course_type=0" + "&token=" + token);
                    startActivity(intent);
                }
                break;
            case R.id.tv_course_remind:
                //课程提醒
                if ("".equals(token)) {
                    intent = new Intent(mcontext, LoginActivity.class);
                    startActivity(intent);
                } else {

                    String isopentixing = sharedPreferences.getString("isopentixing", "1");
                    String tixingtime = sharedPreferences.getString("tixingtime", "08:00");
                    //参数：isOpne提醒状态  time提醒时间    08：00    0关  1开
                    MyLog.e("提醒时间", tixingtime + "   提醒时间");
                    intent = new Intent(mcontext, WebviewActivity.class);
                    intent.putExtra("url", myapp.getSiteurlweb() + "/#/remind?isOpne=" + isopentixing + "&time=" + tixingtime);
                    startActivity(intent);
                }
                break;
            case R.id.ll_teacher:
                //我的老师
                if ("".equals(token)) {
                    intent = new Intent(mcontext, LoginActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(mcontext, WebviewActivity.class);
//                    intent.putExtra("url", myapp.getSiteurlweb() + "/#/group?token=" + token);
                    intent.putExtra("url", myapp.getSiteurlweb() + "/#/myteacher?token=" + token);
                    startActivity(intent);
                }
                break;
            case R.id.ll_addr:
                //我的地址
                if ("".equals(token)) {
                    intent = new Intent(mcontext, LoginActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(mcontext, WebviewActivity.class);
                    intent.putExtra("url", myapp.getSiteurlweb() + "/#/address?token=" + token);
                    startActivity(intent);
                }
                break;
            case R.id.ll_jifen:
                //我的积分
                if ("".equals(token)) {
                    intent = new Intent(mcontext, LoginActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(mcontext, WebviewActivity.class);
                    intent.putExtra("url", myapp.getSiteurlweb() + "/#/integral?token=" + token);
                    startActivity(intent);
                }
                break;
            case R.id.ll_msg:
                //意见反馈
                intent = new Intent(mcontext, MessageCommitActivity.class);
                startActivity(intent);
                break;
            case R.id.ll_video_collect:
                //视频收藏
                if ("".equals(token)) {
                    intent = new Intent(mcontext, LoginActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(mcontext, CollectVideoActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.ll_gobuy_vip:
            case R.id.rl_vip:
                //开通会员
                if ("".equals(token)) {
                    intent = new Intent(mcontext, LoginActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(mcontext, VipActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.ll_jxs:
                //开通会员
                if ("".equals(token)) {
                    intent = new Intent(mcontext, LoginActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(mcontext, JingxiaoshangActivity.class);
                    startActivity(intent);
                }
                break;


        }
    }
}
